<script setup>
import { reactive, ref, onMounted, getCurrentInstance } from 'vue';
const { proxy } = getCurrentInstance();
import requset from '../utils/requset.js'

const tableData = ref([])
const search = ref('')
const dialogVisible = ref(false)
const form = ref({
  name: '',
  maker: '',
  price: '',
  sales: '',
  stock: '',
})

const ruleFormRef = ref(null);

const ipage = ref({
  pageNum: 1,
  pageSize: 5,
  total: 0
})

const rules = {
  name: [
    { required: true, message: '请输入称家居名', trigger: 'blur' }
  ],
  maker: [
    { required: true, message: '请输入称制造商', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    { pattern: /^(([1-9]\d*)|(0))(\.\d+)?$/, message: '请输入数字', trigger: 'blur' }
  ],
  sales: [
    { required: true, message: '请输入销量', trigger: 'blur' },
    { pattern: /^(([1-9]\d*)|(0))$/, message: '请输入数字', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入库存', trigger: 'blur' },
    { pattern: /^(([1-9]\d*)|(0))$/, message: '请输入数字', trigger: 'blur' }
  ]
}

const validMsg = ref({})

onMounted(() => {
  getByPage();
})

const add = (ruleFormRef) => {
  dialogVisible.value = true;
  form.value = {};
  ruleFormRef.resetFields();
  validMsg.value = {};
}

const save = async () => {
  if (form.value.id) {
    const result = await requset.post('/furn/update', form.value).then(res => {
      if (res.code == 0) {
        ElMessage({
          message: '修改成功',
          type: 'success',
        });
        dialogVisible.value = false;
      } else {
        ElMessage({
          message: '修改失败',
          type: 'error',
        });
      }
    })
  } else {
    //表单数据校验是否通过
    await ruleFormRef.value.validate((valid, fields) => {
      if (valid) {
        const result = requset.post('/furn/save', form.value).then(res => {
          console.log(res);
          if (res.code == 0) {
            ElMessage({
              message: '添加成功',
              type: 'success',
            });
            dialogVisible.value = false;
          } else {
            if (res.code == 40000) {
              validMsg.value.name = res.data.name;
              validMsg.value.maker = res.data.maker;
              validMsg.value.price = res.data.price;
              validMsg.value.sales = res.data.sales;
              validMsg.value.stock = res.data.stock;
            } else {
              ElMessage({
                message: '添加失败',
                type: 'error',
              });
            }
          }
        })
      } else {
        ElMessage({
          message: '表单数据格式错误校验失败',
          type: 'error',
        });
        return;
      }
    })
  }

  
  getByPage();
}

const getByPage = async () => {
  const result = await requset.get('/furn/getByPage',
    {
      params: {
        pageNum: ipage.value.pageNum,
        pageSize: ipage.value.pageSize,
        search: search.value
      }
    }).then(res => {
      // console.log(res);
      if (res.code == 0) {
        tableData.value = res.data.records;
        ipage.value.total = res.data.total;
        ipage.value.pageNum = res.data.current;
      } else {
        ElMessage({
          message: '查询失败',
          type: 'error',
        });
      }
    })
}

const deleteClick = async (id) => {
  const result = await requset.post(`/furn/delete/${id}`).then(res => {
    if (res.code == 0) {
      ElMessage({
        message: '删除成功',
        type: 'success',
      });
    } else {
      ElMessage({
        message: '删除失败',
        type: 'error',
      })
    }
  })
  getByPage();
}

const handleEdit = (row) => {
  form.value = row;
  dialogVisible.value = true;
}

const handleCurrentChange = (num) => {
  ipage.value.pageNum = num;
  getByPage();
}

const handlePageSizeChange = (num) => {
  ipage.value.pageSize = num;
  getByPage();
}

</script>

<template>
  <div>
    <div style="margin: 10px 0">
      <el-button type="primary" @click="add(ruleFormRef)">新增</el-button>
      <el-button>其它</el-button>
    </div>
    <!-- 搜索-->
    <div style="margin: 10px 0">
      <el-input v-model="search" placeholder=" 请 输 入 关 键 字 " style="width:30%" clearable></el-input>
      <el-button style="margin-left: 10px" type="primary" @click="getByPage">查询</el-button>
    </div>
    <div class="hometable">
      <el-table :data="tableData" width="auto" border>
        <!-- <el-table-column fixed prop="date" label="日期" sortable /> -->
        <el-table-column prop="name" label="家居名" />
        <el-table-column prop="maker" label="厂商" />
        <el-table-column prop="price" label="价格" />
        <el-table-column prop="sales" label="销量" />
        <el-table-column prop="stock" label="库存" />
        <el-table-column fixed="right" label="操作" width="240">
          <template #default="scope">
            <!-- 增加 popcomfirm 控件，确认删除 -->
            <el-popconfirm title="确定删除吗？" @confirm="deleteClick(scope.row.id)">
              <template #reference>
                <el-button link type="danger">删除</el-button>
              </template>
            </el-popconfirm>
            <el-button link type="primary" size="small" @click="handleEdit(scope.row)">編輯</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div style="margin-top: 10px;">
        <el-pagination background layout="total, sizes, prev, pager, next, jumper" :page-sizes="[5, 10, 20, 30, 40]"
          :page-size="ipage.pageSize" :total="ipage.total" @current-change="handleCurrentChange"
          @size-change="handlePageSizeChange" />
      </div>
    </div>


    <el-dialog title="提示" v-model="dialogVisible" width="30%">
      <el-form :model="form" label-width="120px" :rules="rules" ref="ruleFormRef">
        <el-form-item label="家居名" prop="name">
          <el-input v-model="form.name" style="width: 60%"></el-input>
          <div v-if="validMsg.name">{{ validMsg.name }}</div>
        </el-form-item>
        <el-form-item label="厂商" prop="maker">
          <el-input v-model="form.maker" style="width: 60%"></el-input>
          <div v-if="validMsg.maker">{{ validMsg.maker }}</div>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" type="number" style="width: 60%"></el-input>
          <div v-if="validMsg.price">{{ validMsg.price }}</div>
        </el-form-item>
        <el-form-item label="销量" prop="sales">
          <el-input v-model="form.sales" type="number" style="width: 60%"></el-input>
          <div v-if="validMsg.sales">{{ validMsg.sales }}</div>
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input v-model="form.stock" type="number" style="width: 60%"></el-input>
          <div v-if="validMsg.stock">{{ validMsg.stock }}</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="save(form)">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.hometable {
  padding: 1%;
}
</style>